package PSQueue;

import java.util.ArrayList;

import Service.Variable;
/**
 * @author cyye
 *
 */
public class PSAdvertisement implements AbstractAdvertisement{
    private ArrayList<AbstractMessage> msglist;
	
	public PSAdvertisement() {
		msglist = new ArrayList<AbstractMessage>();
	}	

	/*public ArrayList<AbstractMessage> getAdvertisement() {
		return msglist;
	}*/
		
	public void addAdvertisement(AbstractMessage msg) {
		assert msg!=null;
		PSMessage t_msg = new PSMessage();
		
		//copy msg
		String name = msg.getMsgName();
		assert name!=null;
		t_msg.setMsgName(name);
		
		int type = msg.getMsgType();
		assert Variable.validType(type);
		t_msg.setMsgType(type);
		
		Object value = msg.getValue();
		t_msg.setValue(value);
		
		if(getMessage(name)!=null) {
			System.out.println("Invalid Message: Message " + name + " already exists!");	
		} else
		    msglist.add(t_msg);
	}

	@Override
	public AbstractMessage getMessage(String name) {
		// TODO Auto-generated method stub
		assert name != null;
		for(int i=0;i<msglist.size();i++) {
			if(name.equals(msglist.get(i).getMsgName())) 
				return msglist.get(i);
		}
		return null;
	}

	@Override
	public ArrayList<String> getMsgIDList() {
		// TODO Auto-generated method stub
		ArrayList<String> ids = new ArrayList<String>();
		for(int i=0;i<msglist.size();i++) {
			ids.add(msglist.get(i).getMsgName());
		}
		return ids;
	}
	
	public static AbstractAdvertisement cloneAdvertisement(AbstractAdvertisement adv) {
		assert adv!=null;
		PSAdvertisement result = new PSAdvertisement();
		
		ArrayList<String> ids = adv.getMsgIDList();
		assert ids!=null;
		
		for(int i=0;i<ids.size();i++) {
			String name = ids.get(i);
			AbstractMessage msg = adv.getMessage(name);
			assert msg!=null;									
			result.addAdvertisement(msg);
		}
		
		return result;
	}

}
